#!/usr/bin/env python


import re
import sys
import copy
import logging
from analysis_describe_file import METADATA_EX
from common import UNUSAL_REPLACE


class Variables(object):
    def __init__(self, analysis_describe, variable_name):
        self.describe = analysis_describe
        self.variable_name = variable_name
        self.variable_unit = self.__unit__()
        self.variable_id = self.__variable_id__()
        self.genlab = analysis_describe.genlab
    def __unit__(self):
        return self.describe.varunits[self.describe.variables.index(self.variable_name)]

    def __variable_id__(self):
        number_re = re.compile(r'^\d')
        unusal_character_re = re.compile(r'\W', flags=re.LOCALE)
        variable_id = copy.deepcopy(self.variable_name)
        
        for pattern in UNUSAL_REPLACE:
            variable_id = variable_id.replace(pattern[0], pattern[1])

        match = number_re.match(variable_id)
        if match:
            logging.error(
                'sensor id cannot start with numbers, sensor %s in describe file: %s' % (
                    variable_id, self.describe.describe_file))
            sys.exit(METADATA_EX.rc)

        match = unusal_character_re.findall(variable_id)
        if match:
            logging.error(
                'sensor id only can contain [a-zA-Z0-9_], unusal character: %s, sensor %s in describe file: %s' % (
                    match, variable_id, self.describe.describe_file))
            sys.exit(METADATA_EX.rc)

        if len(variable_id) > 128:
            logging.info(
                'The length of sensorId %s is too long.It will be cut the first 128 character.')
        
        return variable_id